import { Collapse, Modal, notification } from "antd";
import { CSSProperties, memo, useEffect, useState } from "react";
import { useRequest } from "ahooks";
import { view_log } from "../api/request";

const style = { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }

const inputStyle: CSSProperties = {
    whiteSpace: "pre-wrap",
    cursor: "pointer",
    maxHeight: 500,
    overflowY: "auto",
    textAlign: "left",
}
interface Props {
    open: boolean;
    onClose: () => void;
}

const icon = {
    "开始": "img/input.png",
    "LLM": "img/llm.png",
    "条件分支": "img/if.png",
    "知识库": "img/book.png",
    "HTTP": "img/http.png",
    "代码": "img/code.png",
    "结束": "img/output.png",
    "代码执行": "img/code.png",
}

const Log = (props: Props) => {
    const { open, onClose } = props
    const [list, setList] = useState<any[]>([])
    const [api, contextHolder] = notification.useNotification();
    const { success } = Modal;

    const { run: viewLogRun } = useRequest(view_log, {
        manual: true,
        onSuccess: (result) => {
            setList(result.data.log.map((item, index) => ({
                key: index,
                label: <div className="flex">
                    <img style={{ height: 26 }} src={icon[item.type]} />
                    <span className="ml-2 mt-[3px]">{item.type}</span>
                </div>,
                children: <div>
                    <div style={style} onClick={() => {
                        success({
                            title: '输入',
                            width: 800,
                            content: <div className="whitespace-pre-wrap break-words
                             font-mono h-[500px] overflow-auto">
                                {item.input}</div>,
                        });
                    }
                    }>输入：{item.input}</div>
                    <div style={style} onClick={() => {
                        success({
                            title: '输出',
                            width: 800,
                            content: <div className="whitespace-pre-wrap break-words
                            font-mono h-[500px] overflow-auto">
                                {item.output}</div>
                        });
                    }
                    }>输出：{item.output}</div>
                </div>,
            })))
        }
    })

    useEffect(() => {
        if (open) {
            const searchParams = new URLSearchParams(window.location.search);
            const projectId = searchParams.get('projectId');
            viewLogRun(Number(projectId))
        }
    }, [open])

    return <Modal
        title="日志"
        width={700}
        open={open}
        footer={null}
        destroyOnClose={true}
        maskClosable={false}
        onCancel={() => onClose()}>
        <Collapse items={list} />
        {contextHolder}
    </Modal>
}

export default memo(Log);